import _ from 'lodash'
import MediaInfo from './mediainfo-utils'

/* eslint-disable no-mixed-operators */
/* eslint-disable no-bitwise */
export default class Utils {
  static sleep(time) {
    return new Promise(resolve => setTimeout(resolve, time))
  }

  static formatBytes(bytes, decimals = 2) {
    if (bytes === 0) return '0 Bytes'

    const k = 1024
    const dm = decimals < 0 ? 0 : decimals
    const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']

    const i = Math.floor(Math.log(bytes) / Math.log(k))

    // eslint-disable-next-line no-restricted-properties
    return `${parseFloat((bytes / Math.pow(k, i)).toFixed(dm))} ${sizes[i]}`
  }

  static formatBitrate(bytes, decimals = 2) {
    if (bytes === 0) return '0 b/s'

    const k = 1024
    const dm = decimals < 0 ? 0 : decimals
    const sizes = [
      'b/s',
      'Kb/s',
      'Mb/s',
      'Gb/s',
      'Tb/s',
      'Pb/s',
      'Eb/s',
      'Zb/s',
      'Yb/s'
    ]

    const i = Math.floor(Math.log(bytes) / Math.log(k))

    // eslint-disable-next-line no-restricted-properties
    return `${parseFloat((bytes / Math.pow(k, i)).toFixed(dm))} ${sizes[i]}`
  }

  static zeroize(value, length) {
    if (!length) length = 2
    value = `${value}`
    let zeros = ''
    for (let i = 0; i < length - value.length; i += 1) {
      zeros += '0'
    }
    return zeros + value
  }

  static formatDateTime(date) {
    if (date) {
      const time = new Date(date)
      const YYYYMMDD = `${time.getFullYear()}-${time.getMonth() +
        1}-${time.getDate()}`
      const HHMMSS = `${Utils.zeroize(time.getHours())}:${Utils.zeroize(
        time.getMinutes()
      )}:${Utils.zeroize(time.getSeconds())}`
      return `${YYYYMMDD} ${HHMMSS}`
    }
    return ''
  }

  static createUUID() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
      const r = (Math.random() * 16) | 0
      const v = c === 'x' ? r : (r & 0x3) | 0x8
      return v.toString(16)
    })
  }

  static createUUIDString() {
    return Utils.createUUID()
      .split('-')
      .join('')
  }
  static getResUrl(vm, id, type) {
    const { token } = vm.$store.getters
    const mediaType = encodeURIComponent(type)
    return `${
      process.env.VUE_APP_API_SERVER_ADDRESS
    }/api/gateway/outer/download/file?id=${id}&type=${mediaType}&token=${token}`
  }

  static timeToFrameString(t) {
    const time = _.toInteger(t)
    let lS = _.toInteger(time / 1000)
    let lM = _.toInteger(lS / 60)
    lS %= 60
    const lH = _.toInteger(lM / 60)
    lM %= 60
    return `${_.padStart(lH.toFixed(), 2, '0')}:${_.padStart(
      lM.toFixed(),
      2,
      '0'
    )}:${_.padStart(lS.toFixed(), 2, '0')}`
  }

  static formatMediainfo(data) {
    let info = ''
    let video = ''
    let audio = ''
    try {
      if (data) {
        if (data.mediaInfoXml) {
          const mediaInfo = MediaInfo.parseMediainfo(data.mediaInfoXml)
          if (mediaInfo) {
            video = mediaInfo.video
            if (!video && mediaInfo.programs != null) {
              if (mediaInfo.programs.length > 0) {
                const { videos } = mediaInfo.programs[0]
                // eslint-disable-next-line prefer-destructuring
                if (videos) {
                  if (videos[0]) {
                    video = videos[0]
                  }
                }
              }
            }
            if (!audio && mediaInfo.programs != null) {
              if (mediaInfo.programs.length > 0) {
                const { audios } = mediaInfo.programs[0]
                // eslint-disable-next-line prefer-destructuring
                if (audios) {
                  if (audios[0]) {
                    audio = audios[0]
                  }
                }
              }
            }
            if (video) {
              info = `${video.width}x${video.height} `
            }
            if (video.framerate) {
              info += video.framerate
              info += 'fps '
            }
            if (video.duration) {
              info += Utils.timeToFrameString(video.duration)
              info += ' '
            }
            if (video.bitrate) {
              info += video.bitrate / 1000
              info += 'kbps '
            }
            if (audio) {
              if (info.length > 0) {
                info += '| '
              }
              if (audio.codec) {
                info += audio.codec
                info += ' '
              }
              if (audio.bitrate) {
                info += audio.bitrate / 1000
                info += 'kbps '
              }
              if (audio.samplerate) {
                info += audio.samplerate / 1000
                info += 'kHz '
              }
            }
          }
        } else {
          if (data.width && data.height) {
            info = `${data.width}x${data.height}`
            info += ' '
          }
          if (data.aspectX && data.aspectY) {
            info += `${data.aspectX}x${data.aspectY}`
            info += ' '
          }
          if (data.videoFrameTime) {
            info += data.videoFrameTime
            info += 'fps '
          }
          if (data.duration) {
            info += Utils.timeToFrameString(data.duration)
            info += ' '
          }
          if (data.bitrate) {
            info += data.bitrate / 1000
            info += 'kbps '
          }
        }
      }
    } catch (e) {
      console.log(e)
    }
    return info
  }

  static formatAudioinfo(data) {
    let info = ''
    try {
      if (data) {
        if (data.duration) {
          info += Utils.timeToFrameString(data.duration)
          info += ' '
        }
        if (data.bitrate) {
          info += data.bitrate / 1000
          info += 'kbps '
        }
      }
    } catch (e) {
      console.log(e)
    }
    return info
  }

  static dateFormatter() {
    var d = new Date()
    var year = d.getFullYear()
    var month =
      d.getMonth() + 1 < 10 ? '0' + (d.getMonth() + 1) : d.getMonth() + 1
    var day = d.getDate() < 10 ? '0' + d.getDate() : d.getDate()
    return [year, month, day].join('-') + ' ' + ['23', '59', '59'].join(':')
  }
  static dateFormatterLastWeek() {
    var d = new Date(new Date().getTime() - 3600 * 1000 * 24 * 7)
    var year = d.getFullYear()
    var month =
      d.getMonth() + 1 < 10 ? '0' + (d.getMonth() + 1) : d.getMonth() + 1
    var day = d.getDate() < 10 ? '0' + d.getDate() : d.getDate()
    return [year, month, day].join('-') + ' ' + ['00', '00', '00'].join(':')
  }
  static storageFormatBytes(bytes, decimals = 2) {
    if (bytes === 0) return '0 B'

    const k = 1024
    const dm = decimals < 0 ? 0 : decimals
    const sizes = ['B', 'KB', 'M', 'G', 'T', 'PB', 'EB', 'ZB', 'YB']

    const i = Math.floor(Math.log(bytes) / Math.log(k))

    // eslint-disable-next-line no-restricted-properties
    return `${Math.round(parseFloat((bytes / Math.pow(k, i)).toFixed(dm)))} ${
      sizes[i]
    }`
  }
  static deviceStorageFormat(bytes, decimals = 2) {
    if (bytes === 0) return '0G'

    const k = 1024
    const dm = decimals < 0 ? 0 : decimals
    const sizes = ['B', 'KB', 'M', 'G', 'T', 'PB', 'EB', 'ZB', 'YB']

    // eslint-disable-next-line no-restricted-properties
    return `${Math.round(parseFloat((bytes / Math.pow(k, 3)).toFixed(dm)))}${
      sizes[3]
    }`
  }
}
